#include "purchaserecordquery.h"
#include "ui_purchaserecordquery.h"
#include <QMessageBox>
#include <QJsonArray>

PurchaseRecordQueryWindow::PurchaseRecordQueryWindow(QWidget *parent)
    : QWidget(parent)
    , purchaserecordquerywindowUi(new Ui::PurchaseRecordQueryWindow)
    , networkManager(new NetworkManager(this))
{
    purchaserecordquerywindowUi->setupUi(this);
    connect(networkManager, &NetworkManager::queryPurchaseRecordResponseReceived, this, &PurchaseRecordQueryWindow::handleQueryPurchaseRecordResponse);
}

PurchaseRecordQueryWindow::~PurchaseRecordQueryWindow()
{
    delete purchaserecordquerywindowUi;
}

void PurchaseRecordQueryWindow::on_queryButton_clicked()
{
    QString medicineName = purchaserecordquerywindowUi->nameLineEdit->text();
    QString supplier = purchaserecordquerywindowUi->supplierLineEdit->text();
    QString purchaseDate = purchaserecordquerywindowUi->purchaseDateEdit->date().toString(Qt::ISODate);

    if (medicineName.isEmpty() && supplier.isEmpty() && purchaseDate == "2000-01-01") {
        QMessageBox::warning(this, "输入错误", "至少填写一项。");
        return;
    }
    if (purchaseDate == "2000-01-01")
        purchaseDate = "";

    QJsonObject json;
    json["medicine_name"] = medicineName;
    json["supplier"] = supplier;
    json["purchase_date"] = purchaseDate;

    networkManager->queryPurchaseRecord(json);
}

void PurchaseRecordQueryWindow::handleQueryPurchaseRecordResponse(const QJsonObject &response)
{
    int code = response.value("code").toInt();
    QString desc = response.value("desc").toString();

    if (code == 200) {

        QString dataString = response.value("data").toString();
        QJsonDocument jsonDoc = QJsonDocument::fromJson(dataString.toUtf8());
        if (!jsonDoc.isArray()) {
            qDebug() << "Failed to parse 'data' as JSON array.";
            return;
        }

        QJsonArray data = jsonDoc.array();

        qDebug() << data;

        purchaserecordquerywindowUi->resultTable->setRowCount(0);

        for (int i = 0; i < data.size(); ++i) {
            QJsonObject record = data[i].toObject();

            int row = purchaserecordquerywindowUi->resultTable->rowCount();
            purchaserecordquerywindowUi->resultTable->insertRow(row);
            purchaserecordquerywindowUi->resultTable->setItem(row, 0, new QTableWidgetItem(record.value("medicine_name").toString()));
            purchaserecordquerywindowUi->resultTable->setItem(row, 1, new QTableWidgetItem(record.value("supplier").toString()));
            purchaserecordquerywindowUi->resultTable->setItem(row, 2, new QTableWidgetItem(QString::number(record.value("quantity").toInt())));
            purchaserecordquerywindowUi->resultTable->setItem(row, 3, new QTableWidgetItem(record.value("purchase_date").toString()));
        }
    } else {
        QMessageBox::warning(this, "错误", "采购记录查询失败：" + desc);
    }
}
